$(function() {
    var p1 = 0;
    var p2 = 0;
    var p3 = 0;
    var p4 = 0;
    var p5 = 0;
    var p6 = 0;
    var col = '';
    /*首页*/
    $(document).on("pageInit", "#home", function(e, id, page) {        $(".content").scrollTop(0);
        $(".buttons-tab").first().removeClass('buttons-fixed').css('top', 0);
        if($(".buttons-tab").eq(1)){$(".buttons-tab").eq(1).remove();}
        var indicator = {
            loading: false,
            classid: 0
        };

        /*导航标签栏 start*/
        (function($) {
            var win_W = $(document.body).width(),
                tabSwipe = $("#tab_link_wrap");
            var tab_links = $("#tab_link_wrap .tab-link");
            // 每行放置4个按钮
            tab_links.width(win_W / 4);
            // 单个按钮宽度
            var tab_W = tab_links.width();
            var tab_num = tab_links.length;
            //超出部分剩余元素个数
            var res_num = tab_num - 4;
            // res_W超出部分宽度
            var res_W = res_num * tab_W;
            tabSwipe.width(tab_W * tab_num);
            var tab_L = 0;
            var xx, yy, XX, YY, swipeX, swipeY, dx, dy, x_left, flag, initx;
            x_left = 0;
            flag = false;
            initx = true;
            tabSwipe.on("touchstart", function() {

                xx = event.targetTouches[0].screenX;
                yy = event.targetTouches[0].screenY;
                swipeX = true;
                swipeY = true;
            });
            tabSwipe.on("touchmove", function() {
                XX = event.targetTouches[0].screenX;
                YY = event.targetTouches[0].screenY;
                dx = XX - xx;
                dy = YY - yy;
                if (swipeX && Math.abs(dx) - Math.abs(YY - yy) > 0) //左右滑动
                {
                    flag = true;
                    x_left += dx;
                    if (x_left > 0) {
                        $(this).css({
                            left: x_left > 150 ? 150 : x_left
                        });
                    } else {
                        $(this).css({
                            left: x_left < -res_W ? -res_W - 150 : x_left
                        });
                    }
                    event.stopPropagation();
                    event.preventDefault();
                    swipeY = false;
                } else if (swipeY && Math.abs(dx) - Math.abs(YY - yy) < 0) { //上下滑动
                    swipeX = false;
                }
            });
            tabSwipe.on("touchend", function() {
                if (flag) {
                    if (x_left >= 0) {
                        $(this).css({
                            left: 0
                        });
                        x_left = 0;
                    } else if (x_left <= -res_W) {
                        $(this).css({
                            left: -res_W
                        });
                        x_left = -res_W;
                    }
                    /*else{
                    				    	$(this).css({left:x_left });
                    				    }*/
                    event.stopPropagation();
                    flag = false;
                } else { /*响应点击事件*/ }
            });
        })(Zepto);
        /*导航标签栏 end*/


        function custom_init() {
            /*幻灯片配置start*/
            var mySwiper = $(".swiper-container").swiper({
                onInit: function() {
                    var total_num = $(".swiper-slide").length;
                    $(".swiper-slide").each(function(index) {
                        $(this).find(".pull-right").text(index + 1 + "/" + total_num)
                    })
                }
            });
            /*配置标签导航栏*/
            $("#buttons-tab").fixedTab();
        }
        custom_init();



        /*下拉加载 start*/
        function addItems(url, col) {
            $.ajax({
                type: 'GET',
                url: url,
                /*data: */
                dataType: 'json',
                /*timeout: 300,*/
                context: $('.tab.active ul'),
                success: function(data) {
                    var datas = data.array,
                        html = '',
                        url_flag = '';
                    if(data.code == undefined || data.code == null){
                        for (var i in data) {
                            if(data[i].isurl == 1){
                                url_flag = ' external';
                            }

                            if(data[i].ispic == 1){

                                html += '<li><a href=' + data[i].titleurl + ' class="item-link item-content'+url_flag+'"><div class="item-media"><img src=' + data[i].titlepic + '></div><div class="item-inner"><div class="item-text">' + data[i].title + '</div><div class="item_smalltext">'+data[i].smalltext+'</div><div class="item-title-row"><div class="item-title"></div><div class="item-after">' + UnixToDate(data[i].newstime,false) + '</div></div></div></a></li>';
                            }else{
                                html += '<li><a href=' + data[i].titleurl + ' class="item-link item-content'+url_flag+'"><div class="item-inner"><div class="item-text">' + data[i].title + '</div><div class="item_smalltext">'+data[i].smalltext+'</div><div class="item-title-row"><div class="item-title"></div><div class="item-after">' + UnixToDate(data[i].newstime,false) + '</div></div></div></a></li>';
                            }

                        }
                    }else{
                        html = '<li class="no-news">已经到底了</li>';
                    }

                    this.append(html);
                    changePage(col);
                },
                error: function(xhr, type) {
                    console.log('Ajax error!');
                }
            });
        }
        // 初始化栏目显示数据
        // 初始化默认展示栏
        addItems("/api/index/getNews?col=hotnews&p="+p1,'hotnews');
        // 初始化
        $(document).on("click", ".tab-link", function() {
                // var index=$(this).index();

                if ($(this).attr("data-flag") === "true") {
                    col = $(this).attr("col");
                    addItems("/api/index/getNews?col="+col,col);
                    $(this).attr("data-flag", false);

                } else {;
                    return;
                }
            });

        $(page).on('infinite', function() {
            if (indicator.loading) return;
            var self = $(this);
            // 设置flag
            indicator.loading = true;
            setTimeout(function() {
                // 重置加载flag
                indicator.loading = false;
                // 获取当前tab的索引号
                switch (self.find('.infinite-scroll.active').attr('id')) {
                    case "tab1":
                        // classid = 1;
                        col = 'hotnews';
                        addItems("/api/index/getNews?col="+col+"&p="+p1,col);
                        // offset1++;
                        break;
                    case "tab2":
                        // classid = 2;
                        col = 'comnews';
                        addItems("/api/index/getNews?col="+col+"&p="+p2,col);
                        // offset2++;
                        break;
                    case "tab3":
                        // classid = 3;
                        col = 'party';
                        addItems("/api/index/getNews?col="+col+"&p="+p3,col);
                        // offset3++;
                        break;
                    case "tab4":
                        // classid = 4;
                        col = 'zyfw';
                        addItems("/api/index/getNews?col="+col+"&p="+p4,col);
                        // offset4++;
                        break;
                    case "tab5":
                        // classid = 5;
                        col = 'sjs';
                        addItems("/api/index/getNews?col="+col+"&p="+p5,col);
                        // offset5++;
                        break;
                    case "tab6":
                        // classid = 6;
                        col = 'sqxy';
                        addItems("/api/index/getNews?col="+col+"&p="+p6,col);
                        // offset6++;
                        break;

                    default:
                        break;

                };
                $.refreshScroller();
            }, 200)


            // 加载完毕，则注销无限加载事件，以防不必要的加载
            // $.detachInfiniteScroll($('.infinite-scroll').eq(tabIndex));
        });

        /*下拉加载 end*/

    });
    /*详情页*/
    $(document).on("pageInit", "#details", function(e, id, page) {
        $(document).on("click", ".iconfont", function() {

            var newsDetails = $(".newsDetails"),
                orgurl = window.location.href,
                main_text = $(".main_text");

            var obj = {
                url: window.location.href,
                title: newsDetails.find("h1").text(),
                description: '身边人，身边事，社区居民生活的信息平台',
                summary: main_text.find("p").first().text(),
                source: '中国社区网',
                index: $(this).index(),
                image: "http://www.cncn.org.cn/images15/logo.jpg",
                orgurl: orgurl
            }
            share(obj);
        });
        $(function(){
                var timer = null;
                echo.init();
                $(".content").scroll(function(){
                    clearTimeout(timer);
                    timer = setTimeout(function(){
                        echo.render();
                    },120);
                });
            });

    });

    //改变page状态
    function changePage(col){
        switch (col) {
            case 'hotnews':
                p1 += 10;
                break;
            case 'comnews':
                p2 += 10;
                break;
            case 'party':
                p3 += 10;
                break;
            case 'zyfw':
                p4 += 10;
                break;
            case 'sjs':
                p5 += 10;
                break;
            case 'sqxy':
                p6 += 10;
                break;
            default:
                return false;
        }

    }

    $.init();
    // console.log($.device)
});


/**
* 时间戳转换日期
* @param <int> unixTime  待时间戳(秒)
* @param <bool> isFull  返回完整时间(Y-m-d 或者 Y-m-d H:i:s)
* @param <int> timeZone  时区
*/
function UnixToDate(unixTime, isFull, timeZone) {
    if (typeof(timeZone) == 'number') {
        unixTime = parseInt(unixTime) + parseInt(timeZone) * 60 * 60;
    }
    var time = new Date(unixTime * 1000);
    var ymdhis = "";
    ymdhis += time.getUTCFullYear() + "-";
    ymdhis += (time.getUTCMonth() + 1) + "-";
    ymdhis += time.getUTCDate();
    if (isFull === true) {
        ymdhis += " " + time.getUTCHours() + ":";
        ymdhis += time.getUTCMinutes() + ":";
        ymdhis += time.getUTCSeconds();
    }
    return ymdhis;
}
